package com.hula.onion.book.server.spider.platforms.pengjinsuo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.cookie.Cookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by work on 2018/2/2.
 */
@Component("pengingSpider")
public class PengingSpider extends SpiderCommon {

    @Autowired
    private PengingSpiderHelper spiderHelper;

    private static final String LOGIN_URL = "https://secure.penging.com/login/logining.do";


    private static final String ACCOUNT_INFO="http://www.penging.com/selAccount/homePage/selAccount.do";
    @Override
    public CommonResponse execute() {
        String loginStr= HttpUtils.post(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm),
                getHttpContext());
        if(StringUtils.isEmpty(loginStr)){
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        JSONArray jsonArray= JSON.parseArray(loginStr);
        JSONObject loginJson=jsonArray.getJSONObject(1);
        if(!loginJson.getBoolean("success")){
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
        for(Cookie c:getHttpContext().getCookieStore().getCookies()){
            System.out.println(c.getName()+":"+c.getValue());
        }
        if(loginJson.getBoolean("success")){
            String accountStr=HttpUtils.get(ACCOUNT_INFO,getHttpContext());
            return spiderHelper.parseAccountBalance(accountStr);
        }
        return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
    }
}
